package ldh.maker.db;

import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import ldh.maker.constants.TreeNodeTypeEnum;
import ldh.maker.controller.MainController;
import ldh.maker.handle.DbHandle;
import ldh.maker.util.ConnectionFactory;
import ldh.maker.util.UiUtil;
import ldh.maker.vo.DBConnectionData;
import ldh.maker.vo.TreeNode;

import java.sql.*;

/**
 * Created by ldh on 2017/2/26.
 */
public class DbConnectionDb {

    public static void save(DBConnectionData data) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        String sql = "insert into db_info(name, ip, port, user_name, password, tree_node_id) values(?, ?, ?, ?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, data.getNameProperty());
        statement.setString(2, data.getIpProperty());
        statement.setInt(3, data.getPortProperty());
        statement.setString(4, data.getUserNameProperty());
        statement.setString(5, data.getPasswordProperty());
        statement.setInt(6, data.getTreeNode().getId());
        statement.executeUpdate();
        statement.close();
    }

    public static boolean initDbConnection(TreeNode treeNode) throws SQLException {
        boolean hasData = false;
        Connection connection = UiUtil.H2CONN;
        Statement statement = connection.createStatement();
        String sql = "select * from db_info where tree_node_id = " + treeNode.getId();
        ResultSet rs = statement.executeQuery(sql);
        while(rs.next()) {
            DBConnectionData data = new DBConnectionData();
            data.setTreeNode(treeNode);
            data.setNameProperty(rs.getString("name"));
            data.setIpProperty(rs.getString("ip"));
            data.setPortProperty(Integer.valueOf(rs.getString("port")));
            data.setUserNameProperty(rs.getString("user_name"));
            data.setPasswordProperty(rs.getString("password"));
            treeNode.setData(data);
            hasData = true;
            Connection con = ConnectionFactory.getConnection(data);
            data.setConnection(con);
        }
        statement.close();
        return hasData;
    }

    public static void deleteTreeNode(TreeNode treeNode) throws SQLException {
        if (treeNode.getType() != TreeNodeTypeEnum.DB_CONNECTION) return;
        DBConnectionData data = (DBConnectionData) treeNode.getData();
        Connection connection = UiUtil.H2CONN;
        Statement statement = connection.createStatement();
        String sql = "delete db_info where tree_node_id = " + treeNode.getId();
        statement.execute(sql);
        statement.close();
        if (data == null) return;
        ConnectionFactory.close(data.getConnection());
    }
}
